
//
//  vipBuyView.m
//  live1v1
//
//  Created by IOS1 on 2019/5/9.
//  Copyright © 2019 IOS1. All rights reserved.
//

#import "vipBuyView.h"

#import "UIImage+RKImgCategory.h"
#import "YBRechargeType.h"
@interface vipBuyView(){
    NSMutableArray *paylist;
    NSArray *rules;
    
    UIActivityIndicatorView *testActivityIndicator;//菊花
    UIView *rulesView;
    UIView *payListView;
    NSMutableArray *payTypeArray;
    NSMutableArray *coinArray;
    UIButton *gopaybtn;
    UIView *payListBackView;
    NSString *payType;
    NSString *payHref;
    UILabel *getCoinL;
    UILabel *needMoneyL;

}
@property(nonatomic,strong)NSDictionary *seleDic;//选中的钻石字典
//支付宝
@property(nonatomic,copy)NSString *aliapp_key_ios;
@property(nonatomic,copy)NSString *aliapp_partner;
@property(nonatomic,copy)NSString *aliapp_seller_id;
//微信
@property(nonatomic,copy)NSString *wx_appid;
@end

@implementation vipBuyView
- (instancetype)initWithMsg:(NSDictionary *)msg{
    if (self = [super init]) {
        self.frame = CGRectMake(0, 0, _window_width, _window_height);
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        _aliapp_key_ios = [msg valueForKey:@"aliapp_key"];
        _aliapp_partner = [msg valueForKey:@"aliapp_partner"];
        _aliapp_seller_id = [msg valueForKey:@"aliapp_seller_id"];
        //微信的信息
        _wx_appid = [msg valueForKey:@"wx_appid"];
        paylist = [NSMutableArray array];
//        [paylist addObject:@{@"id":@"coin",@"name":@"余额支付"}];
        [paylist addObjectsFromArray:[msg valueForKey:@"paylist"]] ;
        rules = [msg valueForKey:@"vip_rules"];
        payTypeArray = [NSMutableArray array];
        coinArray = [NSMutableArray array];
    
        [self creatUI];
    }
    return self;
}
- (void)closebtnClick{
    [UIView animateWithDuration:0.2 animations:^{
        rulesView.y = _window_height;
    }completion:^(BOOL finished) {
        self.hidden = YES;
    }];
    
}
- (void)show{
    self.hidden = NO;
    [UIView animateWithDuration:0.2 animations:^{
        rulesView.y = _window_height-rulesView.height;
    }];
    
}

- (void)creatUI{
    CGFloat btnWidth;
    CGFloat btnSH = 0.0;
    btnWidth = 110;
    btnSH = 40;
    CGFloat speace = (_window_width-btnWidth*2)/3;
    NSInteger count = 0;
    if (rules.count % 2 == 0) {
        count = rules.count/2;
    }else{
        count = rules.count/2+1;
    }
    rulesView = [[UIView alloc]initWithFrame:CGRectMake(0, _window_height, _window_width, 140+(btnSH + 20)*count+ShowDiff)];
    rulesView.backgroundColor = [UIColor whiteColor];
    rulesView.layer.mask = [PublicObj setViewLeftTop:20 andRightTop:20 andView:rulesView];
    [self addSubview:rulesView];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(rulesView.width/2-50, 20, 100, 20)];
    label.text = YZMsg(@"开通会员");
    label.font = [UIFont boldSystemFontOfSize:14];
    label.textColor = RGB_COLOR(@"#323232", 1);
    label.textAlignment = NSTextAlignmentCenter;
    [rulesView addSubview:label];
    
    UIButton *closeBtn = [UIButton buttonWithType:0];
    closeBtn.frame = CGRectMake(rulesView.width-52, 10, 40, 40);
    [closeBtn setImage:[UIImage imageNamed:@"screen_close"] forState:0];
    closeBtn.imageEdgeInsets = UIEdgeInsetsMake(12, 12, 12, 12);
    [closeBtn addTarget:self action:@selector(closebtnClick) forControlEvents:UIControlEventTouchUpInside];
    [rulesView addSubview:closeBtn];
    for (int j = 0; j < rules.count; j++) {
        
        UIButton *btn = [UIButton buttonWithType:0];
        btn.frame = CGRectMake(speace+j%2 * (btnWidth+speace), 60+(j/2)*(btnSH + 20), btnWidth, btnSH);
        [btn addTarget:self action:@selector(coinBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.clipsToBounds = YES;
        btn.layer.cornerRadius = 5;
        btn.layer.masksToBounds = YES;
        btn.tag = 2000+j;
        btn.titleLabel.font = SYS_Font(13);
        [btn setTitle:minstr([rules[j] valueForKey:@"name"]) forState:0];
        [rulesView addSubview:btn];
        if (j == 0) {
            [btn setBackgroundColor:RGB_COLOR(@"#e5c79b", 1)];
            [btn setTitleColor:RGB_COLOR(@"#8c6936", 1) forState:0];
        }else{
            [btn setBackgroundColor:RGB_COLOR(@"#fafafa", 1)];
            [btn setTitleColor:RGB_COLOR(@"#969696", 1) forState:0];

        }
        [coinArray addObject:btn];
    }
    _seleDic = rules[0];
    gopaybtn = [UIButton buttonWithType:0];
    gopaybtn.frame = CGRectMake(_window_width *0.1, rulesView.height-ShowDiff-50, _window_width*0.8, 40);
    gopaybtn.userInteractionEnabled = YES;
    [gopaybtn setBackgroundImage:[UIImage rk_gradientColorImageFromColors:@[RGB_COLOR(@"#f1d7b2", 1),RGB_COLOR(@"#e0b77a", 1)] gradientType:RKGradientTypeLeftToRight imgSize:gopaybtn.size]];
    gopaybtn.titleLabel.font = SYS_Font(15);
    [gopaybtn setTitle:YZMsg(@"立即开通") forState:0];
    [gopaybtn setTitleColor:RGB_COLOR(@"#8c6936", 1) forState:0];
    [gopaybtn addTarget:self action:@selector(gopaybtnClick) forControlEvents:UIControlEventTouchUpInside];
    gopaybtn.layer.cornerRadius = 20.0;
    gopaybtn.layer.masksToBounds = YES;
    [rulesView addSubview:gopaybtn];
    
    
    needMoneyL = [[UILabel alloc]initWithFrame:CGRectMake(speace, gopaybtn.top-40, 200, 40)];
    needMoneyL.font = SYS_Font(13);
    needMoneyL.textColor = RGB_COLOR(@"#323232", 1);//money_ios
    [needMoneyL setAttributedText:[self getAttstr:[NSString stringWithFormat:@"%@：%@%@ / ¥%@",YZMsg(@"金额"),minstr([_seleDic valueForKey:@"coin"]),[common name_coin],minstr([_seleDic valueForKey:@"money"])] andMoney:minstr([_seleDic valueForKey:@"money"])]];
    [rulesView addSubview:needMoneyL];

}
- (NSAttributedString *)getAttstr:(NSString *)str andMoney:(NSString *)money{
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:str];
    
    [string addAttributes:@{NSForegroundColorAttributeName:RGB_COLOR(@"#969696", 1)} range:NSMakeRange(0, 3)];
    
    [string addAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:255/255.0 green:0/255.0 blue:0/255.0 alpha:1.0]} range:NSMakeRange((str.length - money.length)-1, money.length+1)];
    return string;
}
- (void)coinBtnClick:(UIButton *)sender{
    for (UIButton *btn in coinArray) {
        if (btn == sender) {
            [btn setBackgroundColor:RGB_COLOR(@"#e5c79b", 1)];
            [btn setTitleColor:RGB_COLOR(@"#8c6936", 1) forState:0];

        }else{
            [btn setBackgroundColor:RGB_COLOR(@"#fafafa", 1)];
            [btn setTitleColor:RGB_COLOR(@"#969696", 1) forState:0];

        }
    }
    _seleDic = rules[sender.tag - 2000];
    [needMoneyL setAttributedText:[self getAttstr:[NSString stringWithFormat:@"%@：%@%@ / ¥%@",YZMsg(@"金额"),minstr([_seleDic valueForKey:@"coin"]),[common name_coin],minstr([_seleDic valueForKey:@"money"])] andMoney:minstr([_seleDic valueForKey:@"money"])]];

}
- (void)gopaybtnClick{
    if (paylist.count <= 0) {
        [MBProgressHUD showError:YZMsg(@"支付未开启")];
        return;
    }
    if (payListBackView) {
        [payListBackView removeFromSuperview];
        payListBackView = nil;
    }
    if (!payListBackView) {
        payType = minstr([paylist[0] valueForKey:@"id"]);
        payHref = minstr([paylist[0] valueForKey:@"href"]);
        payListBackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height)];
        payListBackView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        [self addSubview:payListBackView];
        payListView = [[UIView alloc]initWithFrame:CGRectMake(_window_width*0.1, _window_height, _window_width*0.8, 150+paylist.count * 50)];
        payListView.backgroundColor = [UIColor whiteColor];
        payListView.layer.cornerRadius = 20;
        payListView.layer.masksToBounds = YES;
        [payListBackView addSubview:payListView];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(payListView.width/2-50, 10, 100, 20)];
        label.text = YZMsg(@"支付方式");
        label.font = [UIFont boldSystemFontOfSize:14];
        label.textColor = RGB_COLOR(@"#323232", 1);
        label.textAlignment = NSTextAlignmentCenter;
        [payListView addSubview:label];
        
        UIButton *closeBtn = [UIButton buttonWithType:0];
        closeBtn.frame = CGRectMake(payListView.width-52, 0, 40, 40);
        [closeBtn setImage:[UIImage imageNamed:@"screen_close"] forState:0];
        closeBtn.imageEdgeInsets = UIEdgeInsetsMake(12, 12, 12, 12);
        [closeBtn addTarget:self action:@selector(listClosebtnClick) forControlEvents:UIControlEventTouchUpInside];
        [payListView addSubview:closeBtn];
        
        UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(payListView.width/2-50, 40, 100, 20)];
        label2.text = [NSString stringWithFormat:@"%@%@%@",YZMsg(@"购买"),minstr([_seleDic valueForKey:@"name"]),YZMsg(@"会员")];
        label2.font = SYS_Font(11);
        label2.textColor = RGB_COLOR(@"#969696", 1);
        label2.textAlignment = NSTextAlignmentCenter;
        [payListView addSubview:label2];

        getCoinL = [[UILabel alloc]initWithFrame:CGRectMake(0, 65, payListView.width, 25)];
        getCoinL.attributedText = [self getAtt];
        getCoinL.textAlignment = NSTextAlignmentCenter;
        [payListView addSubview:getCoinL];
        
        
        for (int i = 0; i < paylist.count; i ++) {
            UIButton *btn = [UIButton buttonWithType:0];
            btn.frame = CGRectMake(40, i * 50 + 90, payListView.width-80, 50);
            btn.tag = 4000+i;
            [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            [payListView addSubview:btn];
            UIImageView *imgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 17, 16, 16)];
//            if (i == 0) {
//                imgV.image = [UIImage imageNamed:@"coin_Icon"];
//            }else{
                [imgV sd_setImageWithURL:[NSURL URLWithString:minstr([paylist[i] valueForKey:@"thumb"])]];
//            }
            [btn addSubview:imgV];
            UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(imgV.right+5, imgV.top, 100, 16)];
            lable.text = minstr([paylist[i] valueForKey:@"name"]);
            lable.textColor = RGB_COLOR(@"#404040", 1);
            lable.font = SYS_Font(14);
            [btn addSubview:lable];
            
            UIImageView *rightImgV = [[UIImageView alloc]initWithFrame:CGRectMake(btn.width-20, 17.5, 20, 15)];
            [btn addSubview:rightImgV];
            rightImgV.tag = btn.tag+1000;
            if (i == 0) {
                rightImgV.image = [UIImage imageNamed:@"支付选中"];
            }
            [payTypeArray addObject:rightImgV];
            [PublicObj lineViewWithFrame:CGRectMake(0, 49, btn.width, 1) andColor:RGB_COLOR(@"#f0f0f0", 1) andView:btn];
        }
        UIButton *btn = [UIButton buttonWithType:0];
        btn.frame = CGRectMake(0, 90+paylist.count*50+10, payListView.width, 40);
        [btn setTitle:YZMsg(@"立即支付") forState:0];
        [btn setTitleColor:RGB_COLOR(@"#9d8055", 1) forState:0];
        btn.titleLabel.font = [UIFont boldSystemFontOfSize:15];
        [btn addTarget:self action:@selector(goPayMoney) forControlEvents:UIControlEventTouchUpInside];
        [payListView addSubview:btn];
        
    }
    payListBackView.hidden = NO;
    [UIView animateWithDuration:0.2 animations:^{
        payListView.center  = payListBackView.center;
    }];
    
}
- (NSAttributedString *)getAtt{
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",minstr([_seleDic valueForKey:@"coin"]),[common name_coin]] attributes:@{NSFontAttributeName:SYS_Font(20),NSForegroundColorAttributeName: RGB_COLOR(@"#323232", 1)}];
    
    [string addAttributes:@{NSFontAttributeName:SYS_Font(15)} range:NSMakeRange(minstr([_seleDic valueForKey:@"coin"]).length, [common name_coin].length)];
    
    
    //money_ios
    NSMutableAttributedString *string2 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@" / ¥%@",minstr([_seleDic valueForKey:@"money"])] attributes:@{NSFontAttributeName:SYS_Font(20),NSForegroundColorAttributeName: RGB_COLOR(@"#323232", 1)}];
    
    [string2 addAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:255/255.0 green:0/255.0 blue:0/255.0 alpha:1.0]} range:NSMakeRange(3, minstr([_seleDic valueForKey:@"money"]).length+1)];
    [string appendAttributedString:string2];
    return string;
}
- (void)listClosebtnClick{
    [UIView animateWithDuration:0.2 animations:^{
        payListView.y  = _window_height;
    }completion:^(BOOL finished) {
        payListBackView.hidden = YES;
    }];
    
}
- (void)btnClick:(UIButton *)sender{
    payType = minstr([paylist[sender.tag-4000] valueForKey:@"id"]);
    payHref = minstr([paylist[sender.tag-4000] valueForKey:@"href"]);
    UIImageView *imageView = (UIImageView *)[sender viewWithTag:sender.tag + 1000];
    for (UIImageView *img in payTypeArray) {
        if (imageView == img) {
            img.image = [UIImage imageNamed:@"支付选中"];
        }else{
            img.image = [UIImage new];
        }
    }
}
- (void)goPayMoney{
    if (payHref.length>6) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:minstr(payHref)]];
    }else {
        NSDictionary *payPostDic = @{ @"chargeid":[_seleDic valueForKey:@"id"],
                                      @"days":[_seleDic valueForKey:@"days"],
                                      @"money":[_seleDic valueForKey:@"money"],//money_ios
                                      @"coin":[_seleDic valueForKey:@"coin"],
                                    };
        YBWeakSelf;
        if ([payType isEqual:@"ali"]) {
            //支付宝
            [YBRechargeType chargeManeger].aliPayKey = _aliapp_key_ios;
            [YBRechargeType chargeManeger].aliPayPartner = _aliapp_partner;
            [YBRechargeType chargeManeger].aliPaySellerID = _aliapp_seller_id;
            [YBRechargeType chargeManeger].aliCallBackUrl = [h5url stringByAppendingString:@"/appapi/vipback/notify_ali"];
            [[YBRechargeType chargeManeger]selAliPayUrl:@"Vipcharge.getAliOrder" andParameter:payPostDic complete:^(int stateCode, int payType, NSString *msg) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (stateCode == 0) {
                        [weakSelf paySuc];
                    }else{
                        [weakSelf payFail];
                    }
                });
            }];
        }
        if ([payType isEqual:@"wx"]) {
            //微信
            [YBRechargeType chargeManeger].wechatAppID = _wx_appid;
            [[YBRechargeType chargeManeger]selWechatPayUrl:@"Vipcharge.getWxOrder" andParameter:payPostDic complete:^(int stateCode, int payType, NSString *msg) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (stateCode == 0) {
                        [weakSelf paySuc];
                    }else{
                        [weakSelf payFail];
                    }
                });
            }];
        }
        /*rk_20-6-23充值vip不能使用苹果
        if ([payType isEqual:@"apple"]) {
            //苹果
            [YBRechargeType chargeManeger].productID = minstr([_seleDic valueForKey:@"product_id"]);
            [YBRechargeType chargeManeger].appleCallBackUrl = [h5url stringByAppendingFormat:@"/Appapi/Vipback/notify_ios"];
            [[YBRechargeType chargeManeger]selApplePayUrl:@"Vipcharge.getIosOrder" andParameter:payPostDic complete:^(int stateCode, int payType, NSString *msg) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (stateCode == 0) {
                        [weakSelf paySuc];
                    }else{
                        [weakSelf payFail];
                    }
                });
            }];
        }
        */
        if ([payType isEqual:@"balance"]) {
            //余额支付
            [self doCoinPay];
        }
        if ([payType isEqual:@"paypal"]) {
            [[YBRechargeType chargeManeger]selPayPalAndPatameter:payPostDic rechargeType:rechargeType_Vip complete:^(int stateCode, int payType, NSString *msg) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (stateCode == 0) {
                        [weakSelf paySuc];
                    }else{
                        [weakSelf payFail];
                    }
                });

            }];

        }
    }
}

-(void)paySuc {
    if (self.block) {
        self.block();
    }
    [self listClosebtnClick];
    [self closebtnClick];
}
-(void)payFail{
    [self listClosebtnClick];
    [self closebtnClick];
}
- (void)doCoinPay{
    [MBProgressHUD showMessage:@""];
    NSDictionary *subdic = @{
                             @"chargeid":[_seleDic valueForKey:@"id"],
                             @"days":[_seleDic valueForKey:@"days"],
                             @"coin":[_seleDic valueForKey:@"coin"]
                             };
    YBWeakSelf;
    [WYNetworking postWithUrl:@"Vipcharge.balancePay" Dic:subdic Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        if (code == 0) {
            [MBProgressHUD showError:YZMsg(@"支付成功")];
           [weakSelf paySuc];
        }else{
            [MBProgressHUD showError:msg];
            [weakSelf payFail];
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
    }];

}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
